
package com.ttomato.game.mrnom;

import java.util.Random;

import android.util.Log;

public class World {

    static final int WOLRD_WIDTH = 10;
    static final int WOLRD_HEIGHT = 13;
    static final int SCORE_INCRECMENT = 10;
    static final float TICK_INITIAL = 0.5f;
    static final float TICK_DECREMENT = 0.05f;

    public Snake mSnake;
    public Stain mStain;
    public boolean mGameOver = false;
    public int mScore = 0;

    boolean mFields[][] = new boolean[WOLRD_WIDTH][WOLRD_HEIGHT];
    Random mRandom = new Random();
    float mTickTime = 0;
    static float mTick = TICK_INITIAL;

    public World() {
        mSnake = new Snake();
        placeStain();
    }

    private void placeStain() {
        for (int i = 0; i < WOLRD_WIDTH; i++) {
            for (int j = 0; j < WOLRD_HEIGHT; j++) {
                mFields[i][j] = false;
            }
        }

        int len = mSnake.mParts.size();
        SnakePart part;
        for (int i = 0; i < len; i++) {
            part = mSnake.mParts.get(i);
            mFields[part.mX][part.mY] = true;
        }

        int stainX = mRandom.nextInt(WOLRD_WIDTH);
        int stainY = mRandom.nextInt(WOLRD_HEIGHT);

        while (true) {
            if (mFields[stainX][stainY] == false) {
                break;
            }
            stainX += 1;
            if (stainX > WOLRD_WIDTH) {
                stainX = 0;
                stainY += 1;
                if (stainY > WOLRD_HEIGHT) {
                    stainY = 0;
                }
            }
        }

        mStain = new Stain(stainX, stainY, mRandom.nextInt(3));

    }

    public void update(float deltaTime) {
        if (mGameOver) {
            return;
        }

        mTickTime += deltaTime;

        while (mTickTime > mTick) {
            mTickTime -= TICK_INITIAL;
            mSnake.advance();

            if (mSnake.checkBitten()) {
                mGameOver = true;
                return;
            }

            SnakePart head = mSnake.mParts.get(0);

            if (head.mX == mStain.mX && head.mY == mStain.mY) {
                mScore += SCORE_INCRECMENT;
                mSnake.eat();

                if (mSnake.mParts.size() == (WOLRD_WIDTH * WOLRD_HEIGHT)) {
                    mGameOver = true;
                    return;
                } else {
                    placeStain();
                }

                if (mScore % 100 == 0 && mTick - TICK_INITIAL > 0) {
                    mTick -= TICK_INITIAL;
                }
            }
        }
    }
}
